package com.djhu.es.core;

import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.elasticsearch.client.Client;

public class ClientSourcePool implements ClientSource {
    protected GenericObjectPool<Client> internalPool;
    private GenericObjectPool.Config config;

    private PoolableObjectFactory<Client> factory = null;
    private String host;
    private Integer port;

    public ClientSourcePool(GenericObjectPool.Config poolConfig, PoolableObjectFactory<Client> factory){
        this.config = poolConfig;
        this.factory=factory;
        init(config,factory);
    }

    public ClientSourcePool(GenericObjectPool.Config poolConfig, String host, Integer port) {
        config = poolConfig;
        this.host = host;
        this.port = port;
        init(poolConfig,new ClientPoolFactory(host,port));

    }

    public void init(GenericObjectPool.Config poolConfig, PoolableObjectFactory<Client> factory){
        internalPool = new GenericObjectPool<Client>(factory,poolConfig);
    }

    @Override
    public Client getClient() {
        try {
            return internalPool.borrowObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destory() throws Exception {
        this.internalPool.close();
    }

    @Override
    public void returnResource(Client client) throws Exception {
        this.internalPool.returnObject(client);
    }

}
